<?php

namespace console\db\channels;

use Yii;
use yii\helpers\Console;

/**
 * Migration自定义扩展
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class DataPhpMigration extends \console\db\Migration {

    /**
     * @inheritdoc
     */
    abstract public function getTableOptions();

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $data = $this->getTableOptions();
        $count = count($data);
        Console::startProgress($i = 0, $count);
        foreach ($data as $name => $columns) {
            if (!$this->isExistsTable($name)) {
                continue;
            }
            $rows = $this->getData($name . '.php');
            $tableName = '{{%' . $name . '}}';
            $this->truncateTable($tableName);
            $this->batchInsert($tableName, $columns, $rows);
            Console::updateProgress(++$i, $count);
        }
        Console::endProgress("update done." . PHP_EOL);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        foreach ($this->getTableOptions() as $key => $vls) {
            $tableName = '{{%' . $key . '}}';
            if (!$this->isExistsTable($tableName)) {
                continue;
            }
            $this->truncateTable($tableName);
        }
    }

}
